import tkinter as tk
from tkinter import messagebox, ttk
import requests

class AdminWindow:
    def __init__(self, parent, main_app):
        self.main_app = main_app
        self.root = parent
        
        # 清空主窗口
        for widget in self.root.winfo_children():
            widget.destroy()
        
        self.create_widgets()
        self.load_statistics()
        self.load_all_consultations()
    
    def create_widgets(self):
        # 顶部导航栏
        nav_frame = tk.Frame(self.root, bg='#34495e', height=60)
        nav_frame.pack(fill='x', side='top')
        nav_frame.pack_propagate(False)
        
        # 管理员信息
        admin_label = tk.Label(
            nav_frame,
            text="管理员面板",
            font=("Arial", 14, "bold"),
            bg='#34495e',
            fg='white'
        )
        admin_label.pack(side='left', padx=20, pady=20)
        
        # 导航按钮
        nav_buttons_frame = tk.Frame(nav_frame, bg='#34495e')
        nav_buttons_frame.pack(side='right', padx=20, pady=20)
        
        stats_btn = tk.Button(
            nav_buttons_frame,
            text="数据统计",
            command=self.show_statistics,
            font=("Arial", 10),
            bg='#3498db',
            fg='white'
        )
        stats_btn.pack(side='left', padx=5)
        
        consultations_btn = tk.Button(
            nav_buttons_frame,
            text="咨询记录",
            command=self.show_consultations,
            font=("Arial", 10),
            bg='#2ecc71',
            fg='white'
        )
        consultations_btn.pack(side='left', padx=5)
        
        logout_btn = tk.Button(
            nav_buttons_frame,
            text="退出登录",
            command=self.main_app.logout,
            font=("Arial", 10),
            bg='#e74c3c',
            fg='white'
        )
        logout_btn.pack(side='left', padx=5)
        
        # 主内容区域
        self.main_frame = tk.Frame(self.root, bg='#f0f0f0')
        self.main_frame.pack(fill='both', expand=True, padx=20, pady=20)
        
        # 创建统计面板
        self.create_stats_panel()
        
        # 创建咨询记录面板
        self.create_consultations_panel()
    
    def create_stats_panel(self):
        """创建数据统计面板"""
        self.stats_frame = tk.Frame(self.main_frame, bg='#f0f0f0')
        
        # 统计卡片框架
        cards_frame = tk.Frame(self.stats_frame, bg='#f0f0f0')
        cards_frame.pack(fill='x', pady=20)
        
        # 统计卡片
        self.stat_cards = {}
        
        stats_data = [
            {"title": "总用户数", "value": "0", "color": "#3498db", "key": "total_users"},
            {"title": "今日新增", "value": "0", "color": "#2ecc71", "key": "today_users"},
            {"title": "总咨询量", "value": "0", "color": "#e74c3c", "key": "total_consultations"},
            {"title": "活跃用户", "value": "0", "color": "#f39c12", "key": "active_users"}
        ]
        
        for i, stat in enumerate(stats_data):
            card = tk.Frame(cards_frame, bg=stat['color'], relief='raised', bd=1)
            card.grid(row=0, column=i, padx=10, sticky='nsew')
            
            # 让列均匀分布
            cards_frame.columnconfigure(i, weight=1)
            
            title_label = tk.Label(
                card,
                text=stat['title'],
                font=("Arial", 12, "bold"),
                bg=stat['color'],
                fg='white'
            )
            title_label.pack(pady=(15, 5))
            
            value_label = tk.Label(
                card,
                text=stat['value'],
                font=("Arial", 18, "bold"),
                bg=stat['color'],
                fg='white'
            )
            value_label.pack(pady=(5, 15))
            
            self.stat_cards[stat['key']] = value_label
        
        # 热门车型分析
        popular_frame = tk.LabelFrame(
            self.stats_frame,
            text="热门车型分析",
            font=("Arial", 12, "bold"),
            bg='#f0f0f0',
            padx=20,
            pady=20
        )
        popular_frame.pack(fill='x', pady=20)
        
        self.popular_tree = ttk.Treeview(
            popular_frame,
            columns=('type', 'count'),
            show='headings',
            height=6
        )
        self.popular_tree.heading('type', text='车型')
        self.popular_tree.heading('count', text='咨询次数')
        self.popular_tree.column('type', width=200)
        self.popular_tree.column('count', width=100)
        self.popular_tree.pack(fill='x')
    
    def create_consultations_panel(self):
        """创建咨询记录面板"""
        self.consultations_frame = tk.Frame(self.main_frame, bg='#f0f0f0')
        
        # 搜索框架
        search_frame = tk.Frame(self.consultations_frame, bg='#f0f0f0')
        search_frame.pack(fill='x', pady=10)
        
        tk.Label(search_frame, text="搜索:", bg='#f0f0f0', font=("Arial", 12)).pack(side='left', padx=5)
        self.search_entry = tk.Entry(search_frame, font=("Arial", 12), width=30)
        self.search_entry.pack(side='left', padx=5)
        
        search_btn = tk.Button(
            search_frame,
            text="搜索",
            command=self.search_consultations,
            font=("Arial", 10),
            bg='#3498db',
            fg='white'
        )
        search_btn.pack(side='left', padx=5)
        
        refresh_btn = tk.Button(
            search_frame,
            text="刷新",
            command=self.load_all_consultations,
            font=("Arial", 10),
            bg='#2ecc71',
            fg='white'
        )
        refresh_btn.pack(side='left', padx=5)
        
        # 咨询记录表格
        self.consultations_tree = ttk.Treeview(
            self.consultations_frame,
            columns=('id', 'user_name', 'phone', 'budget', 'type', 'scenario', 'time'),
            show='headings',
            height=15
        )
        
        self.consultations_tree.heading('id', text='ID')
        self.consultations_tree.heading('user_name', text='用户姓名')
        self.consultations_tree.heading('phone', text='手机号')
        self.consultations_tree.heading('budget', text='预算范围')
        self.consultations_tree.heading('type', text='偏好车型')
        self.consultations_tree.heading('scenario', text='使用场景')
        self.consultations_tree.heading('time', text='咨询时间')
        
        self.consultations_tree.column('id', width=50)
        self.consultations_tree.column('user_name', width=100)
        self.consultations_tree.column('phone', width=120)
        self.consultations_tree.column('budget', width=100)
        self.consultations_tree.column('type', width=100)
        self.consultations_tree.column('scenario', width=100)
        self.consultations_tree.column('time', width=150)
        
        self.consultations_tree.pack(fill='both', expand=True)
        
        # 绑定双击事件查看详情
        self.consultations_tree.bind('<Double-1>', self.show_consultation_detail)
    
    def show_statistics(self):
        """显示统计面板"""
        self.consultations_frame.pack_forget()
        self.stats_frame.pack(fill='both', expand=True)
        self.load_statistics()
    
    def show_consultations(self):
        """显示咨询记录面板"""
        self.stats_frame.pack_forget()
        self.consultations_frame.pack(fill='both', expand=True)
        self.load_all_consultations()
    
    def load_statistics(self):
        """加载统计数据"""
        try:
            response = requests.get(f"{self.main_app.api_base}/admin/user_stats")
            result = response.json()
            
            if result['success']:
                stats = result['stats']
                
                # 更新统计卡片
                self.stat_cards['total_users'].config(text=str(stats['total_users']))
                self.stat_cards['today_users'].config(text=str(stats['today_users']))
                self.stat_cards['total_consultations'].config(text=str(stats['total_consultations']))
                self.stat_cards['active_users'].config(text=str(stats['active_users']))
                
                # 更新热门车型
                for item in self.popular_tree.get_children():
                    self.popular_tree.delete(item)
                
                for popular_type in stats['popular_types']:
                    self.popular_tree.insert('', 'end', values=(popular_type['type'], popular_type['count']))
                    
        except Exception as e:
            messagebox.showerror("错误", f"加载统计数据失败: {str(e)}")
    
    def load_all_consultations(self):
        """加载所有咨询记录"""
        try:
            response = requests.get(f"{self.main_app.api_base}/admin/consultations")
            result = response.json()
            
            if result['success']:
                # 清空现有数据
                for item in self.consultations_tree.get_children():
                    self.consultations_tree.delete(item)
                
                # 添加新数据
                for consult in result['consultations']:
                    self.consultations_tree.insert('', 'end', values=(
                        consult['id'],
                        consult['user_name'],
                        consult['phone'],
                        consult['budget_range'],
                        consult['preferred_type'],
                        consult['usage_scenario'],
                        consult['created_at']
                    ))
                    
        except Exception as e:
            messagebox.showerror("错误", f"加载咨询记录失败: {str(e)}")
    
    def search_consultations(self):
        """搜索咨询记录"""
        search_term = self.search_entry.get().strip().lower()
        if not search_term:
            self.load_all_consultations()
            return
        
        # 在现有数据中搜索
        for item in self.consultations_tree.get_children():
            values = self.consultations_tree.item(item)['values']
            if (search_term in str(values[1]).lower() or  # 用户姓名
                search_term in str(values[2]).lower() or  # 手机号
                search_term in str(values[3]).lower() or  # 预算范围
                search_term in str(values[4]).lower()):   # 偏好车型
                self.consultations_tree.selection_set(item)
                self.consultations_tree.focus(item)
            else:
                self.consultations_tree.delete(item)
    
    def show_consultation_detail(self, event):
        """显示咨询详情"""
        selection = self.consultations_tree.selection()
        if not selection:
            return
        
        item = selection[0]
        consultation_id = self.consultations_tree.item(item)['values'][0]
        
        try:
            response = requests.get(f"{self.main_app.api_base}/consultation/{consultation_id}")
            result = response.json()
            
            if result['success']:
                consult = result['consultation']
                
                # 创建详情窗口
                detail_window = tk.Toplevel(self.root)
                detail_window.title(f"咨询详情 - ID: {consultation_id}")
                detail_window.geometry("700x500")
                
                # 咨询信息
                info_frame = tk.Frame(detail_window, padx=20, pady=10)
                info_frame.pack(fill='x')
                
                info_text = f"咨询时间: {consult['created_at']}\n预算范围: {consult['budget_range']}\n偏好车型: {consult['preferred_type']}\n使用场景: {consult['usage_scenario']}\n燃料类型: {consult['fuel_type']}\n品牌偏好: {consult['brand_preference']}"
                
                info_label = tk.Label(
                    info_frame,
                    text=info_text,
                    font=("Arial", 11),
                    justify='left',
                    anchor='w'
                )
                info_label.pack(fill='x')
                
                # 分隔线
                ttk.Separator(detail_window, orient='horizontal').pack(fill='x', padx=20, pady=10)
                
                # AI响应
                response_label = tk.Label(
                    detail_window,
                    text="AI推荐结果:",
                    font=("Arial", 12, "bold")
                )
                response_label.pack(anchor='w', padx=20, pady=(0, 10))
                
                response_text = tk.Text(
                    detail_window,
                    font=("Arial", 11),
                    wrap=tk.WORD
                )
                response_text.pack(fill='both', expand=True, padx=20, pady=(0, 20))
                response_text.insert(tk.END, consult['llm_response'])
                response_text.config(state=tk.DISABLED)
                
            else:
                messagebox.showerror("错误", "无法加载咨询详情")
        except Exception as e:
            messagebox.showerror("错误", f"加载详情失败: {str(e)}")